const config = require('./config.js')
const tuner = require('./tuner.js')
const driver = require('./driver.js')

const radio = {
    async init() {
        let status = 0, counter = 0
        while (true) {
            status = await driver.devTEF668x_APPL_Get_Operation_Status()
            switch (status) {
                case 0:
                    await tuner.tableWrite(config.PATCH_TAB)
                    await tuner.tableWrite(config.START_TAB)
                    await tuner.waitMs(50)
                    break;
                case 1:
                    await tuner.tableWrite(config.CLOCK_TAB)
                    await tuner.tableWrite(config.ACTIVE_TAB)
                    await tuner.waitMs(100);
                    break;
                case 2:
                case 3:
                case 4:
                    return
                default:
                    if (++counter < 10) {
                        await tuner.waitMs(5);
                    } else {
                        return
                    }
            }
        }
    },
    powerOn() {
        return driver.devTEF668x_APPL_Set_OperationMode(0)
    },
    powerOff() {
        return driver.devTEF668x_APPL_Set_OperationMode(1)
    },
    setFrequency(frequency) {
        return driver.devTEF668x_Radio_Tune_To(frequency)
    },
    setMute() {
        return driver.devTEF668x_Audio_Set_Mute(1)
    },
    setUnMute() {
        return driver.devTEF668x_Audio_Set_Mute(0)
    },
    setVolume(volume) {
        return driver.devTEF668x_Audio_Set_Volume(volume)//[-60,24]
    },
    async checkStation() {
        const check2TimesLevel = async () => {
            for (let i = 0; i < 2; i++) {
                const { level } = await driver.devTEF668x_Radio_Get_Quality_Data()
                if (level < 25) return false
                await tuner.waitMs(40)
            }
            return true
        }
        if (!await check2TimesLevel()) return false;
        const { usn, wam, offset } = await driver.devTEF668x_Radio_Get_Quality_Data()
        if (usn < 27 && wam < 23 & offset < 100) return true
        return false
    },
}

module.exports = radio
